var common = require("../../../common/common.js").common;

const {$Toast: $Toast} = require("../../../dist/base/index");

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        showInfoTip: false,
        deliver_method: "self",
        arr_id: [],
        arr_count: [],
        goods: [],
        order_goods: [],
        totale_goods: 0,
        totale_price: 0,
        totale_price2: 0,
        all_price: 0,
        yunfei: 10,
        items: [],
        leader_id: 0,
        latitude: "31.997012",
        longitude: "120.861111",
        group: "",
        address: "",
        close_order: "",
        payment_status: 1,
        status: 0,
        leader_change: 2,
        leader_express: 2,
        color_header: "",
        color_main: "",
        color_minor: "",
        confirm_lead: 0,
        buy_info: [],
        form_id: "",
        discount_label: 1,
        choose_discount: -1,
        discount_alert: 0,
        discount: [],
        discount_use: 0,
        discount_unuse: 0,
        discount_price: 0,
        discount_id: "",
        discount_title: "",
        discount_id2: "",
        confirm: 0,
        discount_price2: 0,
        discounted_price: 0,
        click_time: 1,
        confirm_time: 1,
        rp_name: "",
        isIPX: "",
        choose_type: "",
        other_money: 0,
        difference: 0,
        trans_for_free_barrier: "",
        on_off_trans_free: 0,
        typeBox: [],
        time_id: "",
        isDiscount: 1,
        express: 0,
        //快递配送费
        // discount_money:0,
        refund: "",
        //满减
        no_refundGood: 0,
        //存储没有满减活动商品的总和\
        refund_money: 0
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        var isIPX = app.globalData.isIPX;
        this.getBase();
        // let sku_item = options.sku_item;  
        // let arr = sku_item.split('|')
        // var arr_id = [];
        // var arr_count = []
        // var goods = []
        // var items = this.getItems(sku_item)
        // var totale_goods = 0
        // for(var i=0;i<arr.length;i++){
        //   arr_id.push(arr[i].split(',')[0]);
        //   arr_count.push(arr[i].split(',')[1]);
        //   goods[i] = [arr[i].split(',')[0], arr[i].split(',')[1]]
        //   totale_goods += parseInt(arr[i].split(',')[1])
        // }
                var that = this;
        if (options.product_item_id) {
            this.setData({
                product_item_id: options.product_item_id
            });
        }
        this.setData({
            isIPX: isIPX,
            status: 0,
            // arr_id: arr_id,
            // arr_count: arr_count,
            // goods: goods,
            // totale_goods: totale_goods,
            // items: items,
            gid: options.gid,
            payment_status: 1,
            domain: app.globalData.domain.slice(0, -10)
        });
        this.getInfo();
        this.getCloseOrder();
        this.getDiscount();
        this.getKilldis();
        that.getGoods();
        //获取商品信息
        },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        //this.getMyLeaderInfo();//我的团长信息
    },
    /** 
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    getMyLeaderInfo: function() {
        var that = this;
        let leaderName = that.data.leaderName;
        common.request({
            endpoint: "leader/myleaderinfo",
            method: "post",
            data: {
                leader_id_share: "",
                openid: wx.getStorageSync("user").openid
            },
            success: res => {
                if (res.extra.length == 0) {
                    if (this.data.leader_change == "1") {
                        wx.showModal({
                            title: "提示",
                            content: "您还没有选择" + leaderName + "，请先选择" + leaderName + "后再下单！",
                            showCancel: false,
                            success(res) {
                                if (res.confirm) {
                                    wx.redirectTo({
                                        url: "/pages/nearby_group2/nearby_group2"
                                    });
                                }
                            }
                        });
                    } else {
                        wx.showModal({
                            title: "提示",
                            content: "您还没有" + leaderName + "，请点击" + leaderName + "转发的小程序后下单！",
                            showCancel: false,
                            success(res) {
                                if (res.confirm) {
                                    wx.reLaunch({
                                        url: "/pages/index/index"
                                    });
                                }
                            }
                        });
                    }
                }
                res.extra.trans_type.forEach((item, index) => {
                    item.cost = 0;
                });
                this.setData({
                    myleaderinfo: res.extra,
                    yunfei: res.extra.distribution_fee,
                    choose_type: res.extra.trans_type[0].type,
                    other_money: parseFloat(res.extra.trans_type[0].cost),
                    trans_for_free_barrier: res.extra.trans_for_free_barrier,
                    on_off_trans_free: res.extra.on_off_trans_free,
                    typeBox: res.extra.trans_type
                });
                var express = that.data.express;
                var all_price = that.data.all_price;
                console.log("all_price:" + all_price);
                var other_money = that.data.other_money;
                var trans_for_free_barrier = that.data.trans_for_free_barrier;
                var difference = parseFloat(trans_for_free_barrier) - all_price;
                var on_off_trans_free = that.data.on_off_trans_free;
                var typeBox = that.data.typeBox;
                for (var i = 0; i < typeBox.length; i++) {
                    if (typeBox[i].type == 2) {
                        express = typeBox[i].cost;
                        that.setData({
                            express: express
                        });
                    }
                }
                console.log("on_off_trans_free:" + on_off_trans_free);
                console.log("difference:" + difference);
                if (typeBox.length == 1 && typeBox[0].type == 2 && difference <= 0) {
                    other_money = 0;
                    that.setData({
                        other_money: 0
                    });
                }
                let totale_price = parseFloat(all_price) + parseFloat(other_money);
                console.log(all_price + "+" + other_money + "=" + totale_price);
                that.setData({
                    totale_price: totale_price.toFixed(2),
                    totale_price2: parseFloat(all_price).toFixed(2),
                    discounted_price: parseFloat(all_price).toFixed(2),
                    difference: difference.toFixed(2),
                    all_price: parseFloat(all_price).toFixed(2)
                });
            }
        });
    },
    //全局基础配置信息
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                wx.setNavigationBarTitle({
                    title: res.extra.title
                });
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                that.setData({
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    apptitle: res.extra.title,
                    style: res.extra.style,
                    leader_change: res.extra.l_change,
                    leader_express: res.extra.l_express,
                    rp_name: res.extra.rp_name,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    communityName: res.extra.community_title ? res.extra.community_title : "社区"
                });
            }
        });
    },
    //团长切换
    leader_change: function(e) {
        var address = e.currentTarget.dataset.address;
        var is_leader = wx.getStorageSync("my_leader").is_leader;
        let leaderName = this.data.leaderName;
        if (is_leader == 1) {
            wx.showModal({
                title: "提示",
                content: "您自己是" + leaderName + "不能切换" + leaderName + "！"
            });
        }
        if (this.data.leader_change == 1 && is_leader != 1) {
            wx.navigateTo({
                url: "/pages/nearby_group2/nearby_group2"
            });
        }
    },
    getCloseOrder: function() {
        var that = this;
        common.request({
            endpoint: "Order/orderinfo/close_order",
            method: "post",
            success: res => {
                console.log(res);
                that.setData({
                    close_order: res.extra.close_order
                });
            }
        });
    },
    choose: function() {
        var choose = this.data.choose;
        if (choose == 1) {
            choose = 2;
        } else {
            choose = 1;
        }
        this.setData({
            choose: choose
        });
    },
    index_call: function(e) {
        var phone = e.currentTarget.dataset.phone;
        wx.makePhoneCall({
            phoneNumber: phone
        });
    },
    /** 
   * 开始下单
   */
    prePayOrder: function(e) {
        var that = this;
        var status = that.data.status;
        var cart_storage = wx.getStorageSync("cart");
        var name = e.detail.value.name;
        var phone = e.detail.value.phone;
        var house_number = e.detail.value.house_number;
        var remark = e.detail.value.remark;
        let form_id = e.detail.formId;
        var group = that.data.group;
        let leader_id = that.data.myleaderinfo.leader_id;
        console.log(that.data.items);
        if (!name) {
            wx.showModal({
                title: "提醒",
                content: "姓名为必填！",
                showCancel: false
            });
            return false;
        }
        if (!phone) {
            wx.showModal({
                title: "提醒",
                content: "手机号为必填！",
                showCancel: false
            });
            return false;
        }
        var reg2 = /^[1][0-9][0-9]{9}$/;
        if (!reg2.test(e.detail.value.phone)) {
            wx.showModal({
                title: "提示",
                content: "请输入正确的手机号码！",
                showCancel: false
            });
            return false;
        }
        let choose_type = that.data.choose_type;
        if (choose_type != 1) {
            if (!house_number) {
                wx.showModal({
                    title: "提醒",
                    content: "地址为必填！",
                    showCancel: false
                });
                return false;
            }
        }
        that.setData({
            payment_status: 0,
            buy_info: e.detail.value,
            form_id: form_id,
            confirm_lead: 1
        });
    },
    /** 
   * 记录 input 的值
   * e: object 
   */
    recordValue: function(e) {
        let key = e.currentTarget.dataset.name;
        let value = e.detail.value;
        console.log(key);
        this.setData({
            [key]: value
        });
    },
    /** 
   * 重平衡价格
   */
    reBlancePrice: function() {
        // var that = this;
        // var totale_price = that.data.totale_price
        // var yunfei = that.data.yunfei
        // var now_price = parseFloat(totale_price) + parseFloat(yunfei);
        // that.setData({
        //   yunfei: that.data.yunfei,
        //   now_price:now_price.toFixed(2)
        // })
        var that = this;
        if (that.data.deliver_method == "self") {
            console.log(that.data.all_price);
            that.setData({
                totale_price: parseFloat(that.data.discounted_price).toFixed(2),
                totale_price2: parseFloat(that.data.all_price).toFixed(2),
                click_time: 0
            });
        } else if (that.data.deliver_method == "leader") {
            var yunfei = that.data.yunfei;
            let click_time = that.data.click_time;
            var totale_price = parseFloat(that.data.discounted_price) + parseFloat(yunfei);
            that.setData({
                totale_price: totale_price.toFixed(2),
                totale_price2: parseFloat(that.data.all_price).toFixed(2),
                click_time: 1
            });
        }
    },
    /** 
   * 选择运送方式
   */
    selectDeliverMethod: function(e) {
        let method = e.currentTarget.dataset.value;
        this.setData({
            deliver_method: method
        });
        this.reBlancePrice();
    },
    getGoods: function() {
        var that = this;
        // var arr_id = that.data.arr_id;
        // var count_id = that.data.count_id;
        // var time_id = that.data.time_id;
        // var items = that.data.items;
        // var refund = that.data.refund;
                var openid = wx.getStorageSync("user").openid;
        var gid = that.data.gid;
        var product_item_id = that.data.product_item_id;
        common.request({
            endpoint: "Integral/integ_good/show",
            method: "post",
            data: {
                openid: openid,
                gid: gid,
                product_item_id: product_item_id
            },
            success: res => {
                var goods = res.extra;
                that.setData({
                    goods: goods
                });
                this.getMyLeaderInfo();
                //我的团长信息
                        }
        });
    },
    getItems: function(item) {
        if (!item) {
            return [];
        }
        return item.split("|").map(value => {
            let a = value.split(",");
            let t = {
                sku_id: a[0] || 0,
                num: a[1] || 0
            };
            return t;
        });
    },
    getInfo: function() {
        var openid = wx.getStorageSync("user").openid;
        var that = this;
        common.request({
            endpoint: "member/myinfo",
            method: "post",
            data: {
                openid: openid
            },
            header: {
                "content-type": "application/json"
            },
            success(res) {
                console.log(res);
                that.setData({
                    name: res.extra.name,
                    phone: res.extra.phone,
                    house_number: res.extra.address_other,
                    remark: res.extra.remark
                });
            }
        });
    },
    /**
   * 取消后，按钮点击跳转设置
   */
    continueGetSet: function() {
        let that = this;
        wx.getSetting({
            success(res) {
                console.log(res);
            }
        });
        wx.openSetting({
            success(res) {
                console.log(res);
                if (res.authSetting["scope.userInfo"]) {
                    that.getUserInfo();
                }
                if (that.data.warrant || res.authSetting["scope.userInfo"]) {
                    that.setData({
                        showInfoTip: false
                    });
                }
            }
        });
    },
    remind: function() {
        wx.showModal({
            title: "提示",
            content: "请在订单列表页继续支付！",
            success: function() {
                wx.switchTab({
                    url: "/pages/order/order"
                });
            }
        });
    },
    close_confirm: function() {
        this.setData({
            confirm_lead: 0,
            payment_status: 1
        });
    },
    confirm_order: function() {
        var that = this;
        var form_id = that.data.form_id;
        var buy_info = that.data.buy_info;
        let leader_id = that.data.myleaderinfo.leader_id;
        var cart_storage = wx.getStorageSync("cart");
        var status = that.data.status;
        var cart = [];
        var cart_count = "";
        var discount_id = that.data.discount_id;
        var choose_type = that.data.choose_type;
        var delivery_channel = "";
        var time_id = that.data.time_id;
        if (choose_type == 0) {
            delivery_channel = "leader";
        } else if (choose_type == 1) {
            delivery_channel = "self";
        } else {
            delivery_channel = "seller";
        }
        that.setData({
            confirm_lead: 0
        });
        common.request({
            endpoint: "Order/common/prepay-order",
            method: "post",
            data: {
                name: buy_info.name,
                phone: buy_info.phone,
                house_number: buy_info.house_number,
                remark: buy_info.remark,
                leader_id: leader_id,
                delivery_channel: delivery_channel,
                form_id: form_id,
                channel: 4,
                integ_goods_session: that.data.gid,
                integal_pro_item_id: that.data.product_item_id
            },
            success: res => {
                console.log(res, "ressss");
                if (res.message == "下单成功") {
                    $Toast({
                        content: res.message
                    });
                    setTimeout(function() {
                        wx.navigateBack({});
                    }, 600);
                }
                // if (status == 1) {
                //   for (var i = 0; i < cart_storage.length; i++) {
                //     if (cart_storage[i]['select'] == 0) {
                //       cart.push(cart_storage[i])
                //       cart_count += cart_storage[i]['count']
                //     }
                //   }
                //   wx.setStorage({
                //     key: 'cart',
                //     data: cart,
                //   })
                //   wx.setStorage({
                //     key: 'cart_count',
                //     data: cart_count,
                //   })
                // }
                // console.log('下单成功')
                // var order_no = res.order_no
                // wx.requestPayment({
                //   'timeStamp': res.pay.timeStamp,
                //   'nonceStr': res.pay.nonceStr,
                //   'package': res.pay.package,
                //   'signType': res.pay.signType,
                //   'paySign': res.pay.paySign,
                //   'success': function (res) {
                //     console.log(res);
                //     wx.showToast({
                //       title: '支付成功',
                //       icon: 'success',
                //       mask: true,
                //       duration: 3000,
                //       success: function (res) {
                //         wx.showToast({
                //           title: '购买成功！',
                //           icon: 'success',
                //           success: function () {
                //             common.request({
                //               endpoint: 'Order/common/sync-notify',
                //               method: 'post',
                //               data: {
                //                 order_no: order_no,
                //               },
                //               success: res => {
                //                 setTimeout(function () {
                //                   wx.reLaunch({
                //                     url: '/pages/order_confirm/order_confirm?order_no=' + order_no,
                //                   })
                //                 }, 500);
                //               }
                //             })
                //           },
                //         })
                //       }
                //     });
                //   },
                //   'fail': function (res) {
                //     wx.redirectTo({
                //       url: '/pages/order/order',
                //     })
                //   },
                // });
                        },
            fail: err => {
                wx.showModal({
                    title: "提示",
                    content: err.message,
                    success: res => {
                        wx.navigateBack();
                    }
                });
            }
        });
    },
    choose_label: function(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        that.setData({
            discount_label: id
        });
    },
    close_discount: function() {
        this.setData({
            discount_alert: 0
        });
    },
    show_discount: function() {
        var that = this;
        that.setData({
            discount_alert: 1
        });
    },
    choose_discount: function(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        var choose_discount = that.data.choose_discount;
        var discount_price = e.currentTarget.dataset.price;
        var all_price = that.data.all_price;
        var title = e.currentTarget.dataset.title;
        var discount_use = that.data.discount_use;
        var confirm_time = that.data.confirm_time;
        var deliver_method = that.data.deliver_method;
        var choose_type = that.data.choose_type;
        var yunfei = that.data.yunfei;
        var rp_name = that.data.rp_name;
        if (choose_type == 0 || choose_type == 2) {
            that.setData({
                click_time: 0
            });
        }
        if (choose_discount == id) {
            that.setData({
                choose_discount: -1,
                discount_price: 0,
                discount_price2: 0,
                totale_price: parseFloat(all_price).toFixed(2),
                discount_title: discount_use + "个" + rp_name + "可选"
            });
        } else {
            that.setData({
                choose_discount: id,
                discount_price: discount_price,
                totale_price: parseFloat(all_price).toFixed(2),
                discount_id: id,
                discount_title: title,
                discount_price2: discount_price
            });
            if (confirm_time != 0) {
                that.setData({
                    discount_id2: id,
                    confirm_time: confirm_time
                });
            }
            confirm_time++;
        }
    },
    getDiscount: function() {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        var time_id = that.data.time_id;
        common.request({
            endpoint: "Order/voucherinfo/voucher-condition",
            method: "post",
            data: {
                openid: openid,
                items: that.data.items,
                time_id: time_id
            },
            header: {
                "content-type": "application/json"
            },
            success(res) {
                that.setData({
                    discount_title: res.extra.available + "个红包可选",
                    discount: res.extra.voucher,
                    discount_use: res.extra.available,
                    discount_unuse: res.extra.unavailable
                });
            }
        });
    },
    confirm_discount: function() {
        var that = this;
        var discount_price2 = that.data.discount_price2;
        var refund_money = that.data.refund_money;
        var discount_id = that.data.discount_id;
        let discounted_price = that.data.discounted_price;
        var discount_id2 = that.data.discount_id2;
        var discount_price = that.data.discount_price;
        var totale_price = that.data.totale_price;
        console.log("discount_id:" + discount_id);
        console.log("discount_id2:" + discount_id2);
        var choose_type = that.data.choose_type;
        var other_money = that.data.other_money;
        var yunfei = that.data.yunfei;
        var all_price = that.data.all_price;
        var express = that.data.express;
        var trans_for_free_barrier = that.data.trans_for_free_barrier;
        var on_off_trans_free = that.data.on_off_trans_free;
        let good_money = 0;
        // if(discount_id==discount_id2){
                console.log(discount_price);
        good_money = parseFloat(all_price) - parseFloat(discount_price);
        if (good_money <= 0) {
            good_money = .01;
        }
        // }
                var difference = parseFloat(trans_for_free_barrier) - parseFloat(good_money);
        if (choose_type == 2 && on_off_trans_free == 1) {
            other_money = express;
            if (difference <= 0) {
                other_money = 0;
            }
        }
        totale_price = parseFloat(other_money) + parseFloat(good_money);
        let preference = parseFloat(discount_price2) + parseFloat(refund_money);
        that.setData({
            totale_price: parseFloat(totale_price).toFixed(2),
            discount_alert: 0,
            other_money: other_money,
            difference: difference.toFixed(2),
            preference: preference.toFixed(2)
        });
    },
    chooseMethod: function(e) {
        var that = this;
        var discount_price2 = that.data.discount_price2;
        var refund_money = that.data.refund_money;
        let preference = parseFloat(discount_price2) + parseFloat(refund_money);
        var money = e.currentTarget.dataset.money;
        console.log(e.currentTarget.dataset.money);
        console.log(money);
        var type = e.currentTarget.dataset.type;
        var all_price = that.data.all_price;
        var discount_price = that.data.discount_price;
        var express = that.data.express;
        var trans_for_free_barrier = that.data.trans_for_free_barrier;
        var on_off_trans_free = that.data.on_off_trans_free;
        let good_money = parseFloat(all_price) - parseFloat(discount_price);
        if (good_money <= 0) {
            good_money = 0;
        }
        let difference = parseFloat(trans_for_free_barrier) - parseFloat(good_money);
        if (type == 2 && on_off_trans_free == 1 && difference <= 0) {
            money = 0;
        }
        console.log(difference);
        let totale_price = parseFloat(good_money) + parseFloat(money);
        that.setData({
            totale_price: totale_price.toFixed(2),
            choose_type: type,
            other_money: money,
            difference: difference.toFixed(2),
            preference: preference.toFixed(2)
        });
    },
    getKilldis: function() {
        var that = this;
        var time_id = that.data.time_id;
        common.request({
            endpoint: "set/seckill_envelope_isopen",
            method: "post",
            data: {
                time_id: time_id
            },
            header: {
                "content-type": "application/json"
            },
            success(res) {
                that.setData({
                    isDiscount: res.extra.can_use
                });
            }
        });
    },
    refund: function() {
        var that = this;
        var items = that.data.items;
        common.request({
            endpoint: "Order/orderinfo/money_refund",
            method: "post",
            data: {
                sku_id: items
            },
            header: {
                "content-type": "application/json"
            },
            success(res) {
                that.setData({
                    refund: res.extra
                });
                var refund_money = that.data.refund_money;
                if (res.extra.refund_has != "") {
                    refund_money = res.extra.refund_has.refund_limit;
                    that.setData({
                        refund_money: res.extra.refund_has.refund_limit
                    });
                }
                var discount_price2 = that.data.discount_price2;
                let preference = parseFloat(discount_price2) + parseFloat(refund_money);
                that.setData({
                    preference: preference
                });
                that.getGoods();
            }
        });
    }
});